package com.hzit.sb2.util.baidu;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;

import java.util.*;

@Component
public class BaiduToken {
    //设置APPID/AK/SK
    public static final String APP_ID = "21836790";
    public static final String API_KEY = "nWmXnZlKYjg1bjT1gzLYukQZ";
    public static final String SECRET_KEY = "o8s997sct1nBYMb2IPeqTsOkA1xHzB9g";

    public static void main(String[] args) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

//        // 可选：设置网络连接参数
//        client.setConnectionTimeoutInMillis(2000);
//        client.setSocketTimeoutInMillis(60000);
//
//        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
//        System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        String path = "C:\\Users\\Lucas\\Downloads\\sb2\\src\\main\\resources\\static\\test.png";
        JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
        System.out.println(res.toString(2));

    }


    /**
     * 图片从百度提取文字
     * @param path 图片地址
     * @return
     */
    public String getWords(String path){
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
   //     String path = "C:\\Users\\Lucas\\Downloads\\sb2\\src\\main\\resources\\static\\test.png";
        JSONObject res=null;
        if(path.contains("http")){
            res = client.basicGeneralUrl(path, new HashMap<String, String>());
        }else {
            res = client.basicGeneral(path, new HashMap<String, String>());
        }
        String result = "";
        JSONArray jsonArray = res.getJSONArray("words_result");
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()){
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(iterator.next().toString());
            String words = jsonObject.getString("words");
            result += words;
        }
        return result;
    }
}
